<!-- src/views/owner_views/IndexView.vue -->
<template>
  <el-container style="flex-direction: column;">
    <!-- 引入头部导航栏组件 -->
    <OwnerHeader :userInfo="userInfo" />

    <!-- 主体内容 -->
    <el-main>
      <!-- 社区公告 -->
      <el-card class="announcement-box">
        <div slot="header" class="clearfix" style="display: flex; justify-content: space-between; align-items: center;">
          <span>社区公告</span>
          <el-button style="padding: 3px 0" type="text" @click="handleAnnouncementClick">查看更多</el-button>
        </div>
        <div class="announcement-container">
          <div class="announcement-content">
            <div class="announcement-item" v-for="(item, index) in announcements" :key="index">
              <div class="title">{{ item.announcementTitle }}</div>
              <div class="content">{{ item.announcementContent }}</div>
              <div class="time">{{ item.updateTime.replace('T', ' ') }}</div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 访客统计 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="today-total-card">
            <div class="data-card" @click="handleTodayTotalClick">
              <div class="num">{{ todayApply.length }}</div>
              <div class="label">今日访客</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="arrived-card">
            <div class="data-card" @click="handleArrivedClick">
              <div class="num">{{ applyArrive.length }}</div>
              <div class="label">已到访</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="pending-card">
            <div class="data-card" @click="handlePendingClick">
              <div class="num">{{ applyReview.length }}</div>
              <div class="label">待审核</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <div class="button-container">
            <el-button type="primary" icon="el-icon-plus" size="large" @click="handleAddVisitorClick">添加访客</el-button>
            <el-button icon="el-icon-time" size="large" @click="handleHistoryClick">历史记录</el-button>
          </div>
        </el-col>
      </el-row>

      <!-- 社区活动 -->
      <el-card class="activity-card" style="margin-top: 30px;">
        <div slot="header" class="clearfix">
          <span>社区活动</span>
        </div>
        <div class="activity-content">
          <el-card v-for="(activity) in activities" :key="activity.id" class="activity-item" shadow="hover">
            <img :src="activity.imageUrl" alt="活动图片" class="activity-image" />
            <div class="activity-info">
              <div class="activity-name">{{ activity.activityName }}</div>
              <div class="activity-location">地点: {{ activity.location }}</div>
              <div class="activity-time">
                活动时间: {{ activity.activityStart }} - {{ activity.activityDeadline }}
              </div>
              <div class="registration-time">
                报名时间: {{ activity.registrationStart }} - {{ activity.registrationDeadline }}
              </div>
              <div class="activity-status">
                状态:
                <span v-if="activity.status === 1">准备中</span>
                <span v-else-if="activity.status === 2">报名中</span>
                <span v-else-if="activity.status === 3">活动中</span>
                <span v-else-if="activity.status === 4">活动结束</span>
                <span v-else>未知状态</span>
              </div>
            </div>
          </el-card>
        </div>
      </el-card>
    </el-main>

    <!-- 添加访客弹窗 -->
    <el-dialog title="添加访客" :visible.sync="addDialogVisible" width="30%">
      <el-form :model="addForm" label-width="100px">
        <el-form-item label="访客姓名">
          <el-input v-model="addForm.visitorName"></el-input>
        </el-form-item>
        <el-form-item label="访客邮箱">
          <el-input v-model="addForm.visitorEmail"></el-input>
        </el-form-item>
        <el-form-item label="访客手机号">
          <el-input v-model="addForm.visitorPhone"></el-input>
        </el-form-item>
        <el-form-item label="到访地点">
          <el-input v-model="addForm.destination"></el-input>
        </el-form-item>
        <!-- 访客照片 -->
        <el-form-item label="访客照片">
          <el-upload style="text-align:left" ref="pictureUpload" action="#" :list-type="'picture-card'"
            :auto-upload="false" :on-change="handleChange">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <span class="el-upload-list__item-actions">
                <!-- 放大查看缩略图 -->
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <!-- 删除缩略图 -->
                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisiblePicture" :modal="false">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="到访时间范围">
          <el-date-picker v-model="addForm.timeRange" type="datetimerange" range-separator="至" start-placeholder="到访时间"
            end-placeholder="离开时间" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="事由">
          <el-input v-model="addForm.toDo" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddApply">确定</el-button>
      </span>
    </el-dialog>

    <!-- 访客弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%" :before-close="handleCloseDialog">
      <el-table :data="dialogData" style="width: 100%" ref="elTable">
        <el-table-column v-if="isPending" type="selection" width="55"></el-table-column>
        <el-table-column prop="visitorName" label="访客姓名" width="120"></el-table-column>
        <el-table-column prop="visitorImage" label="访客照片" width="150"></el-table-column>
        <el-table-column prop="arriveTime" label="到访时间" width="150"></el-table-column>
        <el-table-column prop="leaveTime" label="离开时间" width="150"></el-table-column>
        <el-table-column prop="toDo" label="事由"></el-table-column>
        <el-table-column prop="state" label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.state === 1">
              <el-tag type="warning">待审核</el-tag>
            </span>
            <span v-else-if="scope.row.state === 2">
              <el-tag type="default">未到访</el-tag>
            </span>
            <span v-else-if="scope.row.state === 3">
              <el-tag type="success">已到访</el-tag>
            </span>
            <span v-else-if="scope.row.state === 4">
              <el-tag type="danger">拒绝到访</el-tag>
            </span>
            <span v-else-if="scope.row.state === 5">
              <el-tag type="info">申请过期</el-tag>
            </span>
            <span v-else>
              <el-tag type="default">{{ scope.row.state }}</el-tag>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <span v-if="isPending" slot="footer" class="dialog-footer">
        <el-button @click="handleReject">拒绝</el-button>
        <el-button type="primary" @click="handleApprove">同意</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import OwnerHeader from '@/components/owner_components/OwnerHeader.vue'; // 引入头部导航栏组件
import { parseJwt } from '@/utils/parseJWT';
import service from '@/utils/request';

export default {
  name: 'IndexView',
  components: {
    OwnerHeader // 注册组件
  },
  data() {
    return {
      //图片上传缩略图所需的属性
      dialogImageUrl: '',
      dialogVisiblePicture: false,
      disabled: false,

      //  图片上传文件列表
      pictureFile: {},

      userInfo: {},
      announcements: [], // 公告列表

      todayApply: [], //今日申请总数
      applyArrive: [], //已到访总数
      applyReview: [], //待审核总数

      applyData: [],
      activities: [], //活动列表

      dialogVisible: false, // 控制弹窗显示
      dialogTitle: '', // 弹窗标题
      dialogData: [], // 弹窗数据
      isPending: false, // 是否为待审核状态

      addDialogVisible: false, // 控制添加访客弹窗的显示
      addForm: { // 添加访客的表单数据
        visitorName: '',
        visitorEmail: '',
        visitorPhone: '',
        visitorImage: '',
        destination: '',
        timeRange: [],
        toDo: '',
        state: 2 // 默认状态为未到访
      },
    };
  },
  mounted() {
    this.userInfo = parseJwt(localStorage.getItem('token')).payload;
    console.log('登录成功,用户信息:', this.userInfo);

    this.getRecentAnnouncement()
    this.getApplyData();
    this.getRecentActivity();


  },
  methods: {
    //图片缩略图组件选择图片后事件
    handleChange(file, fileList) {
      console.log(file, fileList);
      if (fileList.length > 1) {
        this.$message({ type: 'error', message: '只能上传一张图片' });
        this.handleRemove(file);
        console.log(file, fileList);
        return;
      }
      this.pictureFile = file;
    },
    //图片缩略图删除
    handleRemove(file) {
      console.log(file);
      let uploadFiles = this.$refs.pictureUpload.uploadFiles
      for (var i = 0; i < uploadFiles.length; i++) {
        if (uploadFiles[i]['uid'] == file.uid) {
          uploadFiles.splice(i, 1)
        }
      }
    },

    // 图片缩略图放大查看
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisiblePicture = true;
    },

    getRecentAnnouncement() {
      // 获取公告信息
      service.get('/api/user/announcement/getRecentAnnouncements')
        .then(result => {
          console.log('登录成功,公告信息:', result);
          //将result返回的数据赋值给result，即为controller返回的result
          result = result.data;
          if (result.code == 1) {
            console.log('登录成功,公告信息:', result.data);
            this.announcements = result.data.rows;
          } else {
            alert(result.msg);
          }
        });
    },

    getRecentActivity() {
      // 获取活动信息
      service.get('/api/user/activity/getRecentActivity')
        .then(result => {
          //将result返回的数据赋值给result，即为controller返回的result
          result = result.data;
          if (result.code == 1) {
            console.log('登录成功,活动信息:', result.data);
            this.activities = result.data.rows;
          } else {
            alert(result.msg);
          }
        });

    },

    getApplyData() {
      this.applyData = [];
      this.applyArrive = [];
      this.applyReview = [];
      this.todayApply = [];
      //获取当天申请
      service.get(`/api/user/apply/getApplyById/${this.userInfo.id}`)
        .then(result => {
          //将result返回的数据赋值给result，即为controller返回的result
          result = result.data;
          console.log('登录成功,申请信息:', result.data);
          if (result.code == 1) {
            this.applyData = result.data;
            result.data.forEach(item => {
              if (this.isToday(new Date(item.arriveTime))) {
                this.todayApply.push(item);
              }
              if (item.state === 3) {
                this.applyArrive.push(item);
              } else if (item.state === 1) {
                this.applyReview.push(item);
              }
            });
          } else {
            alert(result.msg);
          }
        });
    },
    openDialog(title, data, isPending) {
      this.dialogData = [];
      this.dialogData = data;
      this.dialogTitle = title;
      this.isPending = isPending;
      this.dialogVisible = true;
    },
    handleCloseDialog(done) {
      this.dialogVisible = false;
      done();
    },

    /**
     * 批量同意申请
     */
    handleApprove() {
      // 获取已选择的行数据
      const selectedRows = this.$refs.elTable.selection;

      // 提取已选择数据的 id
      const ids = selectedRows.map(row => row.id);
      if (ids.length === 0) {
        alert('请选择要同意的申请');
        return;
      }
      console.log('同意申请', ids);
      //同意申请
      service.post('/api/user/apply/allowApply', ids)
        .then(result => {
          //将result返回的数据赋值给result，即为controller返回的result
          result = result.data;
          if (result.code == 1) {
            // 刷新页面
            this.getApplyData();
          } else {
            alert(result.msg);
          }
        });
      this.$message.success('已同意申请');
      this.getApplyData();
      this.handleCloseDialog();
    },

    /**
     * 批量拒绝申请
     */
    handleReject() {
      // 获取已选择的行数据
      const selectedRows = this.$refs.elTable.selection;

      // 提取已选择数据的 id
      const ids = selectedRows.map(row => row.id);

      if (ids.length === 0) {
        alert('请选择要拒绝的申请');
        return;
      }
      console.log('同意申请', ids);
      //同意申请
      service.post('/api/user/apply/refuseApply', ids)
        .then(result => {
          //将result返回的数据赋值给result，即为controller返回的result
          result = result.data;
          if (result.code == 1) {
            this.getApplyData();
          } else {
            alert(result.msg);
          }
        });
      this.$message.success('已拒绝申请');
      this.getApplyData();
      this.handleCloseDialog();
    },
    /**
     * 打开添加访客弹窗
     */
    handleAddVisitorClick() {
      this.addDialogVisible = true; // 打开弹窗
    },
    handleAddApply() {
      let newData = {
        userId: this.userInfo.id,
        arriveTime: this.addForm.timeRange[0],
        leaveTime: this.addForm.timeRange[1],
        visitorName: this.addForm.visitorName,
        visitorEmail: this.addForm.visitorEmail,
        visitorPhone: this.addForm.visitorPhone,
        destination: this.addForm.destination,
        visitorToDo: this.addForm.toDo,
        state: 2,
        visitorImage: '',
      }
      const fromData = new FormData();
      fromData.append('image', this.pictureFile.raw);
      service.post('/api//upload/aliyun', fromData)
        .then(result => {
          result = result.data;
          console.log('上传成功', result);
          if (result.code == 1) {
            newData.visitorImage = result.data;

            console.log("---------------");
            console.log(newData);
            console.log(newData.visitorImage);
            // 提交添加访客申请
            service.post('/api/user/apply/addApply', newData)
              .then(result => {
                result = result.data;
                if (result.code === 1) {
                  this.$message.success('添加访客成功');
                  this.addDialogVisible = false; // 关闭弹窗
                  this.getApplyData(); // 刷新数据
                } else {
                  this.$message.error(result.msg);
                }
              })
              .catch(error => {
                this.$message.error('添加访客失败');
                console.error(error);
              });
          } else {
            alert(result.msg);
          }
        })
    },
    handleTodayTotalClick() {
      let data = this.todayApply;
      this.openDialog('今日访客', data, false);
    },
    handleArrivedClick() {
      let data = this.applyArrive;
      this.openDialog('已到访', data, false);
    },
    handlePendingClick() {
      let data = this.applyReview;
      this.openDialog('待审核', data, true);
    },
    handleHistoryClick() {
      let data = this.applyData;
      this.openDialog('待审核', data, true);
    },
    isToday(date) {
      const today = new Date();
      return date.getFullYear() === today.getFullYear() &&
        date.getMonth() === today.getMonth() &&
        date.getDate() === today.getDate();
    },
    handleAnnouncementClick() {
      this.$router.push('/owner/announcements');
    }
  }
};
</script>

<style scoped>
.el-container {
  height: 100vh;
}

.el-main {
  padding: 20px;
}

.announcement-box {
  margin-bottom: 20px;
  height: 200px;
  overflow: hidden;
  position: relative;
}

.announcement-container {
  height: 100%;
  overflow: hidden;
}

.announcement-content {
  animation: scroll 10s linear infinite;
}

.announcement-item {
  padding: 10px;
  margin-bottom: 10px;
}

@keyframes scroll {
  0% {
    transform: translateY(40%);
  }

  100% {
    transform: translateY(-100%);
  }
}

.announcement-item .title {
  font-weight: bold;
}

.announcement-item .content {
  color: #666;
  margin: 5px 0;
}

.announcement-item .time {
  color: #999;
  font-size: 12px;
}

.data-card {
  text-align: center;
  padding: 20px 0;
}

.data-card .num {
  font-size: 24px;
  font-weight: bold;
}

.today-total-card {
  background-color: #409EFF;
  color: #fff;
}

.arrived-card {
  background-color: #67C23A;
  color: #fff;
}

.pending-card {
  background-color: #E6A23C;
  color: #fff;
}

.button-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.button-container .el-button {
  margin: 10px 0;
  width: 100%;
}

.activity-card {
  margin-bottom: 20px;
}

.activity-content {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: flex-start;
  /* 左对齐 */
}

.activity-item {
  flex: 0 0 calc(33.33% - 20px);
  /* 固定大小，不自动填充 */
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px;
  box-sizing: border-box;
}

.activity-image {
  width: 100%;
  max-width: 150px;
  height: auto;
  border-radius: 8px;
}

.activity-description {
  margin-top: 10px;
  text-align: center;
  font-size: 14px;
}





/* 修改上传图片组件框大小 */
::v-deep .el-upload--picture-card {
  width: 100px;
  height: 100px;
}

::v-deep .el-upload {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item-thumbnail {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

::v-deep .avatar {
  width: 100px;
  height: 100px;
}
</style>